package com.devx.hessian.server;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.stereotype.Service;

import com.dexv.hessian.IPersonService;
import com.dexv.hessian.Person;

@Service("personService")
public class PersonService implements IPersonService {

  	private static Map<Integer,Person> people = new ConcurrentHashMap<Integer, Person>();
	private static AtomicInteger keyGenerator = new AtomicInteger(0);
	
	@PostConstruct
	public void init()
	{
		System.out.println("Person Service Loaded");
	}
	
	public Person add(Person person) {
		if (person.getId() == null) {
			Integer id = keyGenerator.addAndGet(1);
			person.setId(id);
			people.put(id,person);
			System.out.println("SERVER ADD PERSON : " + id);
			return person;
		} else {
			throw new RuntimeException("Person already exists!");
		}
		
	}

	public void update(Person person) {
		if (person.getId() != null) {
			System.out.println("SERVER UPT PERSON : " + person.getId());
			people.put(person.getId(), person);
		} else {
			throw new RuntimeException("Person must be saved first!");
		}
	}
	
	public void delete(Integer personId) {
		
		System.out.println("SERVER DEL PERSON : " + personId);
		
		people.remove(personId);
	}

	public Person get(Integer id) {
		System.out.println("SERVER GET PERSON : " + id);
		return people.get(id);
	}

}
